package com.example.zjx8969.myapplication.dialogManager

import android.content.DialogInterface
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext


open class QueuedDialogTask<T>(private val callBack: QueueDialogModel) : DialogInterface.OnDismissListener {

    suspend fun showNextAvailableDialog(): Boolean = withContext(Dispatchers.Default) launch@{
        if (!ifConditionSatisfyPre()) return@launch false
        val t = doInBackground<T>()
        if (!ifConditionSatisfySuffix(t)) return@launch false
        withContext(Dispatchers.Main) {
            val dialog: AbstractQueueDialog = createDialog().also {
                it?.addOnDialogDismissListener(this@QueuedDialogTask)
            } ?: return@withContext false
            dialog.showDialog()
        }
    }

    open fun ifConditionSatisfyPre(): Boolean = true
    open fun <T> doInBackground(): T? = null
    open fun <T> ifConditionSatisfySuffix(t: T?): Boolean = true

    open fun createDialog(): AbstractQueueDialog? {
        throw IllegalStateException("此方法必须重写")
    }

    override fun onDismiss(p0: DialogInterface?) {
        Log.d("queueDialog", "className=${javaClass.canonicalName} dismiss")
        callBack.showNextDialogByOrder()
    }

}
